<?php

/***************************************************************\
* FILE:		/sys/access.inc
* SECTION:	core - access
* FUNCTION:	provide access control functionality
* USES:		$PAGE['directory_id_tree']
*		$_SESSION[]
* INCLUDES:	none
* PRODUCES:	$ACCESSLIST
* LAUNCHES:	none
\***************************************************************/

/**
* generate accesslist for current directory and user and store it in
* $ACCESSLIST
*/
function generate_accesslist() {
	global $PAGE, $ACCESSLIST;
	$ACCESSLIST = generate_accesslist_for_directory_for_user($PAGE['directory_tree'], $_SESSION);
}

/**
 * generate an array containing the access parameters for the given user
 * on the given directory
 */
function generate_accesslist_for_directory_for_user($directory_tree, $user_info) {
	
	$ACCESSLIST = array();
	
	for ($i = 0; $i < count($directory_tree); $i++)
		$dirs .= $directory_tree[$i]['dir_id'].",";
	$dirs .= "0";
	
	$where = "ACCESS_RULE.action_id = ACCESS_ACTION.action_id AND \n\tACCESS_RULE.dir_id IN ($dirs) AND \n\t(\n\t\t";
	if ($user_info['user_id']) {
		$where .= "ACCESS_RULE.user_id = {$user_info['user_id']} OR \n\t\t";
		for ($i = 0; $i < count($user_info['user_groups']); $i++)
			$groups .= $user_info['user_groups'][$i].",";
		$groups .= "-1";
		$where .= "ACCESS_RULE.usergroup_id IN ($groups) OR \n\t\t";
	}
	$where .= "ACCESS_RULE.ipstring LIKE '".$_SERVER["REMOTE_ADDR"]." - ".$_SERVER["HTTP_X_FORWARDED_FOR"]."' OR \n\t\t";
	$where .= "ACCESS_RULE.guest > 0\n\t)";
	
	$order = "rank ASC";
	
	$sql = db_query_select(array(array('allow'),array('action')), array("ACCESS_RULE", "ACCESS_ACTION"), $where, $order);
	
	$sqlresult = db_do_query($sql);
	
	if (db_num_rows($sqlresult) < 1)
		errorpage(3);
	
	while ($result = db_fetch_array($sqlresult)) {
		array_push($ACCESSLIST, $result);
	}
	
	return $ACCESSLIST;
}

function has_access($str) {
	global $ACCESSLIST;
	return check_access_in_list($str, $ACCESSLIST);
}

function has_any_add_access() {
	global $ACCESSLIST;
	return check_access_in_list("^ADD", $ACCESSLIST, 1);
}

function check_access($str) {
	global $ACCESSLIST;
	if (!check_access_in_list($str, $ACCESSLIST))
		errorpage(5);
}

/**
 * checks whether the given access parameter is in the supplied access list
 */
function check_access_in_list($desired_string, $accesslist, $regexp=0) {
	
	for ($i = 0; $i < count($accesslist); $i++)
		if (eregi( ($regexp ? $desired_string : "^{$desired_string}$"), $accesslist[$i]['action']))
			if ($accesslist[$i]['allow'])
				return 1;
			else if (!$regexp)
				return 0;
	
	return 0;
	
}

function printAL() {
	global $ACCESSLIST;
	echo "<ol>";
	for ($i = 0; $i < count($ACCESSLIST); $i++)
		echo "<li>{$ACCESSLIST[$i]['action']} - {$ACCESSLIST[$i]['allow']}";
	echo "</ol>";
}

?>
